package com.wenhai.concurrency.thread.pool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @ClassName CompletionServiceDemo
 * @Description {@link java.util.concurrent.CompletionService} 示例
 * @Author 谢文海
 * @Date 2021/4/26 1:29
 * @Version 1.0
 **/
public class CompletionServiceDemo {
    public static void main(String[] args) throws Exception {
        MyCallable c1 = new MyCallable("1", 5);
        MyCallable c2 = new MyCallable("2", 4);
        MyCallable c3 = new MyCallable("3", 3);
        MyCallable c4 = new MyCallable("4", 2);
        MyCallable c5 = new MyCallable("5", 1);
        List<Callable<String>> callables = new ArrayList<>();
        callables.add(c1);
        callables.add(c2);
        callables.add(c3);
        callables.add(c4);
        callables.add(c5);
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 10, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
        CompletionService<String> cs = new ExecutorCompletionService<>(poolExecutor);
        for (int i = 0; i < 5; i++) {
            cs.submit(callables.get(i));
        }

        for (int i = 0; i < 5; i++) {
            System.out.printf("等待打印第 %s 个返回值 %s\n", i + 1, cs.take().get());
        }
    }
}
